#include "./include/kvset.h"
#include <stdio.h>
#include <string.h>

char membuf[5000]={0};
static kv_t g_kv;
void membufErase(int handle,int pos,char val)
{
    int i=0,addNum = 0;
    for(i=0;i<pos;i++){
        addNum = handle+i;
        printf("membufErase %d\n",addNum);
        //membuf[addNum]=val;
    }
}

void membufWrite(int handle,int pos,char * data,int size)
{
    int i=0,addNum = 0;
    for(i=0;i<size;i++){
        addNum = handle+i+pos;
        printf("membufWrite %d\n",addNum);
        //membuf[addNum]=data[i];
    }
    
}

unsigned int membufRead(int handle,int pos,char * data,int size)
{
    int i=0,addNum = 0;
    for(i=0;i<size;i++){
        addNum = handle+i+pos;
        printf("membufRead %d\n",addNum);
        //data[i] = membuf[handle+i+pos];
    }
    return i;
}

#define partition_open(a)  (a)
#define partition_erase(a,b,c)      membufErase(a,b,c)
#define partition_write(a,b,c,d)    membufWrite(a,b,c,d)
#define partition_read(a,b,c,d)     membufRead(a,b,c,d)

static int kv_flash_erase(kvblock_t *block, int pos, int size)
{
    int ret = pos + size <= block->size;
    if (ret)
        partition_erase(block->kv->handle, block->id * block->size + pos, 1);

    return ret;
}

static int kv_flash_write(kvblock_t *block, int pos, void *data, int size)
{
    int ret = pos + size <= block->size;
    if (ret)
        partition_write(block->kv->handle, block->id * block->size + pos, data, size);

    return ret;
}

static int kv_flash_read(kvblock_t *block, int pos, void *data, int size)
{
    int ret;
    ret = partition_read(block->kv->handle, block->id * block->size + pos, data, size);
    return ret;
}

static flash_ops_t flash_ops = {
    .write = kv_flash_write,
    .erase = kv_flash_erase,
    .read = kv_flash_read
};


void kv_test(const char *partition)
{
    kv_t *kv = &g_kv;
    char buf[10];
    char buf2[10];
    memset(buf,0,sizeof(buf)); 
    memset(buf2,0,sizeof(buf2)); 
    memset(kv, 0, sizeof(kv_t));
    kv->handle = partition_open(partition);
    kv->ops    = &flash_ops;
	//getch();
	printf("%s %s %d KV:%d\n",__FILE__,__func__,__LINE__,kv->handle);
    if (kv->handle >= 0) {
        //partition_info_t *lp = hal_flash_get_info(kv->handle);
        partition_info_t lp ;
        //aos_assert(lp);
        lp.sector_size = 255;
        lp.length =  sizeof(membuf);
        uint8_t *mem        = membuf;
        int      block_size =  lp.sector_size;
        int      block_num  =  lp.length /  lp.sector_size;

        kv_init(kv, mem, block_num, block_size);

        kv_set(kv, "test", "1234", 5);
        kv_set(kv, "test2", "123456", 7);


        kv_get(kv, "test", buf, 5);
        kv_get(kv, "test2", buf2, 7);

        printf("test get:%s\n", buf);
        printf("test get:%s\n", buf2);
    }
}


int main(void){
    kv_test(membuf);
    getch();

}
